package com.voucher.dao;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class ceshisd {

    // 定义 MIME 类型到文件扩展名的映射
    private static final Map<String, String> MIME_TYPE_EXTENSION_MAP = new HashMap<>();

    static {
        MIME_TYPE_EXTENSION_MAP.put("application/pdf", ".pdf");
        MIME_TYPE_EXTENSION_MAP.put("text/html;charset=UTF-8", ".html");
        MIME_TYPE_EXTENSION_MAP.put("application/msword", ".doc");
        MIME_TYPE_EXTENSION_MAP.put("application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".docx");
        MIME_TYPE_EXTENSION_MAP.put("application/vnd.ms-excel", ".xls");
        MIME_TYPE_EXTENSION_MAP.put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx");
        MIME_TYPE_EXTENSION_MAP.put("image/jpeg", ".jpg");
        MIME_TYPE_EXTENSION_MAP.put("image/png", ".png");
        // 可以根据需要添加更多的 MIME 类型映射
    }

    public static void main(String[] args) {
        String loginUrl = "http://222.177.166.226:28080/login.jsp";
        String username = "330270";
        String password = "Mx123456";
        String fdId = "19517a30a83d3d651df06894576952a7";
        String savePath = "D://file.docx";

        CookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
//                .setRedirectStrategy(new LaxRedirectStrategy()) // 启用自动处理重定向
                .build();

        try {
            // === 1. 登录（确保 Cookie 存储）===
            HttpPost loginPost = new HttpPost(loginUrl);
            List<BasicNameValuePair> loginParams = new ArrayList<>();
            loginParams.add(new BasicNameValuePair("j_username", username));
            loginParams.add(new BasicNameValuePair("j_password", DesEncryptUtil.encrypt(password)));
            loginPost.setEntity(new UrlEncodedFormEntity(loginParams, "UTF-8"));

            HttpResponse loginResponse = httpClient.execute(loginPost);
            System.out.println("登录状态: " + loginResponse.getStatusLine().getStatusCode());

            // 关键：打印登录后的 Cookies
            System.out.println("登录后 Cookies:");
            cookieStore.getCookies().forEach(c ->
                    System.out.println(c.getName() + "=" + c.getValue()));

            // === 2. 增强会话验证 ===
            HttpGet validateRequest = new HttpGet("http://222.177.166.226:28080/user/profile");
            HttpResponse validateResponse = httpClient.execute(validateRequest);

            // 处理可能的登录重定向（如跳转回登录页）
            if (validateResponse.getStatusLine().getStatusCode() == 302) {
                String redirectUrl = validateResponse.getFirstHeader("Location").getValue();
                if (redirectUrl.contains("login.jsp")) { // 检测是否被重定向到登录页
                    throw new RuntimeException("登录失败，Cookie 无效");
                }
            }

            // 验证响应内容是否包含登录后的数据
            String validateContent = EntityUtils.toString(validateResponse.getEntity());
            if (!validateContent.contains("用户信息")) { // 根据实际页面关键词调整
                throw new RuntimeException("会话验证失败");
            }

            // === 3. 构建下载请求（确保携带 Cookies）===
            String downloadUrl = "http://222.177.166.226:28080/sys/attachment/sys_att_main/sysAttMain.do"
                    + "?method=download"
                    + "&fdId=" + URLEncoder.encode(fdId, "UTF-8")
                    + "&downloadType=manual"
                    + "&downloadFlag=" + System.currentTimeMillis();

            HttpGet httpGet = new HttpGet(downloadUrl);
            httpGet.setHeader("Referer", "http://222.177.166.226:28080/main.do");
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)...");

            // === 4. 执行下载（自动处理重定向和 Cookies）===
            HttpResponse downloadResponse = httpClient.execute(httpGet);
            System.out.println("最终状态码: " + downloadResponse.getStatusLine().getStatusCode());

            // 确保响应内容是文件（而非 HTML 错误页）
            Header contentType = downloadResponse.getEntity().getContentType();
            if (contentType != null && contentType.getValue().contains("application/pdf")) {
                try (InputStream is = downloadResponse.getEntity().getContent();
                     FileOutputStream fos = new FileOutputStream(savePath)) {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, bytesRead);
                    }
                }
                System.out.println("文件下载成功: " + savePath);
            } else {
                String errorContent = EntityUtils.toString(downloadResponse.getEntity());
                System.out.println("错误响应: " + errorContent);
                throw new RuntimeException("下载失败，内容类型不符");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}